package com.uniplaza.app.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.android.volley.components.volley.TimestampDeserializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.uniplaza.app.volley.ApiConstant;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Kim on 2017/1/11.
 * 工具类
 */

public class Utils {

    /**
     * 打印日志
     *
     * @param tag 标题
     * @param msg 要打印的内容
     */
    public static void log(String tag, String msg) {
        if (ApiConstant.APP_DBG) {
            Log.i(tag, msg);
        }
    }

    /**
     * 打印日志 重要信息 红色显示
     *
     * @param tag 标题
     * @param msg 要打印的内容
     */
    public static void logError(String tag, String msg) {
        if (ApiConstant.APP_DBG) {
            Log.e(tag, msg);
        }
    }

    //给一个图片背景
    public static Bitmap drawBg4Bitmap(int color, Bitmap orginBitmap, Context mcontext) {
        Paint paint = new Paint();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            paint.setColor(mcontext.getResources().getColor(color, null));
        } else {
            paint.setColor(mcontext.getResources().getColor(color));
        }

        Bitmap bitmap = Bitmap.createBitmap(orginBitmap.getWidth(),
                orginBitmap.getHeight(), orginBitmap.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawRect(0, 0, orginBitmap.getWidth(), orginBitmap.getHeight(), paint);
        canvas.drawBitmap(orginBitmap, 0, 0, paint);
        return bitmap;
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate(Long date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDates(Long date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        return dateString;
    }

    private static Toast toast = null;

    /**
     * toast 提示
     *
     * @param context 上下文
     * @param text    显示的内容
     */
    public static void toast(Context context, String text) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
        toast.show();
    }


    /**
     * 隐藏显示的软键盘
     *
     * @param context  当前activity
     * @param view 获取了焦点的输入框
     */
    public static void hideKeyboard(Context context, View view) {
        try {
            InputMethodManager inputMgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMgr.hideSoftInputFromWindow(view.getWindowToken(), 0);
        } catch (Exception e) {

        }
    }

    /**
     * 显示软键盘
     *
     * @param context 当前上下文
     */
    public static void showKeyboard(final Activity context) {
        TimerTask showKeyboardTask = new TimerTask() {
            @Override
            public void run() {
                InputMethodManager inputMgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMgr.showSoftInput(context.getCurrentFocus(), InputMethodManager.SHOW_FORCED);
            }
        };

        Timer timer = new Timer();
        timer.schedule(showKeyboardTask, 10);
    }

    // md5 加密
    @NonNull
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }


    /**
     * 将json数据解析为对象
     *
     * @param type 数据类型
     * @param json 需要解析的json数据
     * @return 对象
     */
    @Nullable
    public static <T> T jsonToBean(Type type, String json) {
        try {
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(Timestamp.class, new TimestampDeserializer());
            Gson gson = gsonBuilder.create();
            return gson.fromJson(json, type);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //保存登录信息
//    public static void SaveLogin(LoginBean array, Context text, Handler handler) {
//
//        Application.getInstance().setIsLogin(true);
//        Application.getInstance().setLogin(array, handler);
//
//        ConfigUtils Utils = ConfigUtils.getInstance(text, Constant.CONFIGKEY.ANTSCART);
//        Utils.setObject(Constant.CONFIGKEY.SAVELOGIN, array);
//        LoginActivity activity = LoginActivity.getLoginActivity();
//        if (activity != null) {
//            activity.finish();
//            activity.overridePendingTransition(R.anim.scale_in, R.anim.jump_static_out);
//        }
//    }


    /**
     * 保留两位小数
     *
     * @param number 输入随意数字
     * @return 返回保留两位小数打数字
     */
    public static String decimals(double number) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(number);
    }

    /**
     * 获取屏幕宽度
     *
     * @param context 上下文
     * @return 屏幕宽度
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    //获取语言code
//    public static String getLanguageCode(boolean ison) {
//        Locale locale = Application.getInstance().getResources().getConfiguration().locale;
//
//        String language = "";
//        if (locale == null || TextUtils.isEmpty(locale.getLanguage())) {
//            language = Constant.DEFULT_LUNGUAGE_;
//            return language;
//        }
//
//        language = locale.getLanguage();
//
//
//        if (ison) {
//            if (locale.getCountry().length() != 0) {
//                language += "-" + locale.getCountry().toLowerCase();
//            }
//        }
//
//        return language;
//
//    }


    //设置语言
//    public static void setLanguage(Locale language) {
//        Resources resources = Application.getInstance().getBaseContext().getResources();
//        Configuration config = resources.getConfiguration();
//        config.locale = language;
//        Application.getInstance().setNowLunguage(language);
//        DisplayMetrics dm = resources.getDisplayMetrics();
//        resources.updateConfiguration(config, dm);
//        resources.flushLayoutCache();
//        if (MainActivity.instance != null)
//            MainActivity.instance.resetText();
//        ConfigUtils UtilsLanguage = ConfigUtils.getInstance(Application.getInstance().getBaseContext(), MainConfig.VALUE.LANGUAGE);
//        UtilsLanguage.setObject(MainConfig.VALUE.LANGUAGE, language);
//        return;
//    }

    /**
     * 获取后缀名
     *
     * @param path 文件路径
     * @return 后缀名 字符串
     */
    @Nullable
    public static String getFileLastName(String path) {
        int start = path.lastIndexOf(".");
        int end = path.length();
        if (start != -1 && end != -1) {
            return path.substring(start + 1, end);
        } else {
            return null;
        }
    }

    public static String data(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (date.getTime() / 1000) + "";
    }

    /**
     * 启动loginActivity
     *
     * @param context 上下文
     * @return 登录返回 true 未登录返回 false
     */

//    public static void toLogin(Activity context) {
//        if (!Application.getInstance().isLogin() && context != null) {
//            Intent startLogin = new Intent(context, LoginActivity.class);
//            context.startActivity(startLogin);
//            context.overridePendingTransition(R.anim.scale_in, R.anim.jump_static_out);
//        }
//    }

    //退出登录
//    public static void LoginOut(Context mContext, boolean toast) {
//        Application.getInstance().setIsLogin(false);
//        Application.getInstance().setUserBean(null);
//        ConfigUtils Utils = ConfigUtils.getInstance(mContext, Constant.CONFIGKEY.ANTSCART);
//        Utils.setObject(Constant.CONFIGKEY.SAVELOGIN, null);
//
//        if (toast) {
//            toast(mContext, mContext.getString(R.string.outnin));
//        }
//
//        if (MainActivity.instance != null) {
//            MainActivity.instance.clearInstance();
//            MainActivity.instance.setPoint(false);
//        }
//
//        Intent intents = new Intent(mContext, MainActivity.class);
//        mContext.startActivity(intents);
//
//    }

    // 根据手机的分辨率将px(像素)的单位转成dp
    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static int dp2px(Context context, int dp) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return (int) ((dp * displayMetrics.density) + 0.5);
    }

}
